<template>
  <div class="termination">
    <ListTab
      v-model="tabStatus"
      :show-header="!showMobilePage"
      :tabs="tabs"
      :max-badge="{ num: 100, str: '99+' }"
      is-table
      @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="min-fill-page termination-list">
      <div v-if="!showMobilePage" class="filter">
        <FilterInput ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" is-show-config show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        <createBtn v-if="hasRouteAuth('crm:termination:create')" style="margin-right: 10px;" @click.native="toCreate"/>
        <MoreOpeator
          ref="moreOpeatorRef"
          :list="[
            { label: '批量抄送', handelClick: handleSendMsg },
            { label: '复制链接', handelClick: batchCopyLink }
          ]"
        />
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 300px;">
          <u-table
            v-if="list.items.length"
            ref="tableRef"
            :data="list.items"
            :height="setTableHeight"
            :row-height="49"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"/>
            <u-table-column :min-width="handleTdWidth()" align="left" label="审批单号" label-class-name="diy-cell" class-name="diy-cell">
              <template slot-scope="scope" slot="header">
                <div class="diyHeader">{{ scope.column.label }}</div>
              </template>
              <template slot-scope="scope">
                <processSn :is-expedited="scope.row.isExpedited">
                  <div v-if="scope.row.terminationNum" style="cursor:pointer;color:#406EFF;" @click="toDetail(scope.row)">
                    <ToolTip :content="handleSnNumber(scope.row.terminationNum)" is-can-click @handelClick="toDetail(scope.row)" />
                  </div>
                  <div v-else>--</div>
                </processSn>
              </template>
            </u-table-column>
            <u-table-column align="left" label="解约说明" min-width="200">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.terminationExplain" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="平台" min-width="200">
              <template slot-scope="scope">
                <div class="flex-center">
                  <PlatformIcon :data="scope.row.platform" />
                  {{ scope.row.platform || '--' }}
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="账号名称" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.accounts" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="账号ID" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.resourceCode" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="供应商名称" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.channelName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="签单签约经纪" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.agentName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="解约日期" min-width="160" sortable="custom" prop="terminationTime">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.terminationTime,'YYYY/MM/DD')" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态">
              <template slot-scope="scope">
                <StatusText
                  v-if="scope.row.status || scope.row.status===0"
                  :color="['#FFBC3D','#FD8546', '#FF4E5F', '#999', '#31CC9C','#406EFF'][scope.row.status]"
                  :text="scope.row.status | filterStatus"
                />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="当前节点">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.currentNode" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="当前处理人" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.currentHandler" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="所属部门" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.department" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人">
              <template slot-scope="scope">
                <CheckUserInfo :user-id="scope.row.createUserId" :label="scope.row.createUser" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="160" prop="createTime" sortable="custom">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime,'YYYY/MM/DD HH:mm')" />
              </template>
            </u-table-column>
            <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
              <template slot-scope="scope">
                <div class="operate">
                  <div v-if="scope.row.status !== 0 && !showMobilePage" class="button-text br" @click="toDetail(scope.row)">查看</div>
                  <MoreOpeator
                    :list="[
                      {
                        label: '查看',
                        handelClick: () => {toDetail(scope.row)},
                        auth: scope.row.status !== 0 && showMobilePage
                      },{
                        label: '复制',
                        handelClick: () => {handlerCreateNew(scope.row)},
                        disabled: scope.row.status === 0 || !hasRouteAuth('crm:termination:create')
                      },{
                        label: '编辑',
                        handelClick: () => {toEdit(scope.row)},
                        disabled: setEditDisable(scope.row)
                      },{
                        label: '删除',
                        handelClick: () => {toDelete(scope.row)},
                        disabled: setDelDisable(scope.row)
                      }
                    ]"
                  >
                    <div v-if="!showMobilePage" slot="button" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="table-dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!list.isInit" slot="empty" empty-text="暂无数据" mode="table" style="padding-bottom: 0;" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <MoreOpeator
              ref="moreOpeatorRef"
              :list="[
                { label: '批量抄送', handelClick: handleSendMsg },
                { label: '复制链接', handelClick: batchCopyLink }
              ]"
              show-mobile-icon
            />
            <createBtn
              v-if="hasRouteAuth('crm:termination:create')"
              mobile-table
              @click.native="toCreate"/>
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
      <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @handleSender="handleBatchSender" />
    </div>
  </div>
</template>
<script>
// import axios from 'axios';// 取消未完成请求
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
// 组件
import ListTab from '@/components/ListTab';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import PlatformIcon from '@/components/Common/platformIcon';
// filter
import { energyStatus as filterStatus } from '@/filters/status';
import { expeditedOptions } from '@/filters/status';
import { CURRENT_NODE_MODULE } from '@/utils/const';
// api
import { tabList, terminationList, deleteTermination } from '@/api/termination';
import { platformList } from '@/api/select';
import { getDepartmentAll } from '@/api/config';
import { format } from '@/filters/date';
import { showModal } from '@/utils/message';
import { PROCESS_TYPE } from '@/utils/const/process';
import { commonOptions } from '@/utils/tools';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import tableSelections from '@/mixins/tableSelections';
import copyLink from '@/mixins/copyLink';
import schedule from '@/mixins/schedule';

export default {
  filters: {
    filterStatus
  },
  components: {
    ListTab,
    EmptyPlaceholder,
    createBtn,
    MoreOpeator,
    DiversAuditorDialog,
    PlatformIcon
  },
  mixins: [TableAdaptive, mobileTable, filterObjStoreMixin, tableSelections, copyLink, schedule],
  data() {
    return {
      tabs: [],
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      tabStatus: -1,
      page: 1,
      perPage: 20,
      paramsObj: {},
      listLoading: false,
      deptTreeList: [],
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      isUmyTable: true,
      sortType: '',
      sortName: '',
      cancelToken: null,
      orderPlatformOption: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'terminationNum', name: '审批单号', labelWidth: '100px', type: 'input' },
        { keyword: 'terminationExplain', name: '解约说明', labelWidth: '100px', type: 'input' },
        { keyword: 'channelName', name: '供应商名称', labelWidth: '100px', type: 'input' },
        { keyword: 'accountName', name: '账号名称', labelWidth: '100px', type: 'input' },
        { keyword: 'accountId', name: '账号ID', labelWidth: '100px', type: 'input' },
        { keyword: 'agentName', name: '签单签约经纪', labelWidth: '100px', type: 'input' },
        { keyword: 'createUser', name: '创建人', labelWidth: '100px', type: 'input' },
        { keyword: 'comment', name: '评论', type: 'input', labelWidth: '100px' },
        // 下拉
        { keyword: 'status', name: '状态', type: 'select', options: commonOptions },
        { keyword: 'departmentId', name: '所属部门', type: 'cascaderSelect', childrenVal: 'children', options: this.deptTreeList },
        {
          keyword: 'currentNode',
          name: '当前节点',
          type: 'loadMoreSelect',
          valueName: 'name',
          directShow: true,
          multiple: true,
          extendParams: { type: CURRENT_NODE_MODULE.TERMINATION },
          labelName: 'name',
          placeholder: '当前节点',
          searchkeyword: 'keyword',
          apiUrl: 'admin/common/currentNodes'
        },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        { keyword: 'platformId', name: '下单平台', type: 'select', options: this.orderPlatformOption },
        // 日期
        { keyword: 'terminationTime', name: '解约日期', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    },
    rangeKeyArr() {
      return [{
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time'
      }, {
        attr: 'terminationTime',
        start: 'terminationStartTime',
        end: 'terminationEndTime',
        type: 'time'
      }];
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  created() {
    this.queryDeptTreeList();
    this.platformList();
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'terminationCreate' || from.name === 'terminationEdit' || from.name === 'terminationDetail') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (this.$route.meta.isChange) {
      this.fetchData();
    } else {
      const { accountId, platformId } = this.$route.query;
      if (accountId && (platformId || platformId === 0)) {
        this.$set(this.paramsObj, 'accountId', accountId);
        this.$set(this.paramsObj, 'platformId', Number(platformId));
      }
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        this.fetchData(true);
      }
    }
  },
  methods: {
    hasRouteAuth,
    format,
    getDetailLink(item) {
      if (!item.status) return null;
      return `${location.origin}/#/supplierPage/terminationDetail?terminationId=${item.id}&processId=${item.processId}`;
    },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        result.data.forEach((i) => {
          i.label = i.value;
          i.value = i.id;
        });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    getTabs() {
      const params = this.formatParams();
      delete params.tabStatus;
      tabList(params).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.tabs = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = { items: [] };
      this.fetchData(true);
    },
    fetchData(reset = false) {
      // if (this.cancelToken) this.cancelToken.cancel('cancel');
      // const source = axios.CancelToken.source();// 用于取消请求
      // this.cancelToken = source;
      this.getTabs();
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams();
      terminationList(params).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
        this.list.isInit = false;
      }).catch(err => {
        this.listLoading = false;
        console.log(err);
      });
    },
    formatParams() {
      const params = _.cloneDeep(this.paramsObj);
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(['currentNode'], params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.tabStatus = this.tabStatus;
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      return params;
    },
    setEditDisable(data) {
      return !(data.status === 0 && data.createUserId === this.userInfo.id);
    },
    setDelDisable(data) {
      const statusArr = [0, 2, 3, 5];// 草稿、未过审 已作废、待提交
      return !(statusArr.includes(data.status) && (data.createUserId === this.userInfo.id || this.hasRouteAuth('crm:termination:delete')));// 除审批中和已完成状态且为创建人或者有删除权限
    },
    toCreate() {
      this.$router.push({
        name: 'terminationCreate'
      });
    },
    toEdit(row) {
      this.$router.push({
        name: 'terminationEdit',
        params: {
          id: row.id
        }
      });
    },
    toDetail(row) {
      this.filterObjStore(PROCESS_TYPE.TERMINATION);
      this.$router.push({
        name: 'terminationDetail',
        query: {
          terminationId: row.id,
          processId: row.processId,
          fromList: 1
        }
      });
    },
    toDelete(row) {
      showModal('是否确定删除?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        deleteTermination(row.id).then(res => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.resetItemSelected(row.id);
          this.fetchData();
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.queryClick();
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.sortName = '';
      this.sortType = '';
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    handlerCreateNew(row) { // 再次发起（复制）
      const routeUrl = this.$router.resolve({
        name: 'terminationEdit',
        params: {
          id: row.id
        },
        query: {
          reapplyId: row.processId,
          createNew: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.termination{
  .termination-list{
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 24px 55px 24px;
  }
  .operate{
    @include flexStyle($align: center);
  }
  .filter {
    @extend .operate;
    margin-bottom: 16px;
    .create-btn{
      height: 32px;
      font-size: 14px;
      padding: 0 15px;
    }
  }
}
</style>
